
// 登录路由
const express = require('express');
const bcrypt = require("bcrypt");//加密
const gravatar = require('gravatar');//头像
const jwt = require('jsonwebtoken');//token
const keys = require("../../config/keys");
const passport = require("passport")

//创建路由
const router = express.Router();
const User = require("../../models/User");


// @route  GET api/users/test
// @desc   返回的请求的json数据
// @access public
router.get("/test", (req, res) => {
    res.json({ msg: "user works" });
  });



//登录  post  api/users/login
// 返回的请求的json数据
router.post("/login",(req,res)=>{
    const email = req.body.email;
    const password = req.body.password;
    //查询数据库
    User.findOne({email}).then(user =>{
        if(!user){
            return res.status(404).json("用户不存在！");
        }
        //密码匹配
        bcrypt.compare(password, user.password)
        .then(isMatch =>{
            if(isMatch){
                const rule = {
                    id:user.id, 
                    name:user.name,
                    avatar:user.avatar,
                    identity:user.identity
                };
                //jwt.sign("规则","加密名字","过期时间","箭头函数")
                jwt.sign(rule, keys.secretOrKey, {expiresIn:3600},(err, token)=>{
                    if(err) throw err;
                    res.json({
                        success:true,
                        token:"Bearer " + token
                    })
                })
                 
            }else{
                return res.status(404).json("密码错误！")
            }
        })
    })

}) 
//登录获取用户信息
router.get("/current",passport.authenticate("jwt",{session:false}), (req, res)=>{
    res.json({
        //要显示的用户信息
        id:req.user.id,
        name:req.user.name,
        email:req.user.email,
        identity:req.user.identity
    });
})

//POST 注册  api/users/register
router.post("/register",(req,res)=>{
    // console.log(req.body)
    //查询数据库中是否拥有邮箱
    User.findOne({email:req.body.email}).then((user)=>{
        if(user){
            return res.status(400).json("邮箱已被注册！")
        }else{
            //需要
            var avatar = gravatar.url(req.body.email, {s: '200', r: 'pg', d: 'mm'});
            const newUser = new User({
                name:req.body.name,
                email:req.body.email,
                avatar,
                password:req.body.password,
                identity: req.body.identity
            })

            //进行加密
            bcrypt.genSalt(10, function(err, salt){
                bcrypt.hash(newUser.password,salt, (err,hash)=>{
                    if(err) throw err;//错误
                    newUser.password = hash;//成功
                    //成功存储账号
                    newUser.save()
                            .then(user => res.json(user))
                            .catch(err => console.log(err))
                })
            })
        }
    })
})

//暴露出去
module.exports = router;